//#include"cloud_disk.h"
#include"cmd_tast.h"
#include<shadow.h>
#include"server_login.h"
#include "mysql_io.h"
#include "jwt.h"

//判断用户名是否正确
int server_login1(cmd_tast *t,MYSQL* p_mysql)
{
    printf("LoginCheck1.\n");
    char saltbuf[256]={0};//存盐值

   printf("username entered by user: %s\n",t->content);

    int ret= mysql_get_user_data(p_mysql,saltbuf,t->content,"salt");

   
    //1、用户不存在
    if(ret==-1)
    {
        t->peerfd=0;

        char tmp[]="username error,please enter again.";
        memset(t->content,0,sizeof(t->content));
        strncpy(t->content,tmp,strlen(tmp));

        t->cmdType=CMD_TYPE_LOGIN1_ERROR;
        return 0;
    }


    //2、用户存在
    t->peerfd=-1;

    memset(t->content,0,sizeof(t->content));
    strncpy(t->content,saltbuf,strlen(saltbuf));

    t->cmdType=CMD_TYPE_LOGIN1_OK;
    return 0;
}


//判断密码是否正确
int server_login2(cmd_tast *t,MYSQL* p_mysql)
{
    printf("LoginCheck2.\n");
    char pathbuf[256]={0};//存用户初始路径
    printf("cryptpasswd sent by user: %s\n",t->content);
    mysql_get_user_path(p_mysql,pathbuf,t->content,"pwd");


    //1、登录失败
    if(strlen(pathbuf)==0)
    {
        t->peerfd=0;

        char contentbuf1[]="Login failed.";
        memset(&t->content,0,sizeof(t->content));
        strncpy(t->content,contentbuf1,strlen(contentbuf1));

        t->cmdType=CMD_TYPE_LOGIN2_ERROR;
        
        return 0;

    }


    //2、登录成功

    t->peerfd=0;
//生成令牌
    const char* sub = "xixi";
    const char* iss = "mnc";
    const char* aud = "xiuxiu";
    const char* secret_key = "123456";
    int exp_duration_seconds = TOKENTIME;

    char* jwt = generate_jwt(sub, iss, aud, secret_key, exp_duration_seconds);

    if (jwt) {
        printf("\nGenerated JWT: %s\n", jwt);
     //   l8w8jwt_free(jwt); // 释放生成的 JWT
    } else {
        printf("\nJWT 生成失败\n");
    }

   //传递令牌
    memset(&t->content,0,sizeof(t->content)); 
    strncpy(t->content,jwt,strlen(jwt));
   // printf("\n t->connect:%s\n",t->content);
    
     //   l8w8jwt_free(jwt); // 释放生成的 JWT

    t->cmdType=CMD_TYPE_LOGIN2_OK;

    memset(&t->path,0,sizeof(t->path));
    strncpy(t->path,pathbuf,strlen(pathbuf));

    return 0;
}
